'use strict'

const Service = require('egg').Service
const path = require('path')
const fs = require('fs')
const sendToWormhole = require('stream-wormhole')
const awaitStreamReady = require('await-stream-ready')

class ArchiveService extends Service {
  async getArchiveList(queryInfo) {
    // 如果没有 queryInfo.pagenum，说明是获取全部
    if (!queryInfo.pagenum) {
      let resultAll = await this.app.mysql.query('SELECT * FROM c_archive ')

      return this.ctx.getRESTfulData(
        {
          total: resultAll.length,
          archiveList: resultAll,
        },
        '获取所有档案列表成功',
        200
      )
    }

    let resultAll = await this.app.mysql.query(
      `SELECT 
      *
      FROM c_archive 
      WHERE archive_name like ?`,
      ['%' + queryInfo.query + '%']
    )

    let result = await this.app.mysql.query(
      `SELECT 
      *
      FROM c_archive 
      WHERE archive_name like ?
      LIMIT ?,?`,
      [
        '%' + queryInfo.query + '%',
        parseInt(queryInfo.pagenum - 1) * queryInfo.pagesize,
        parseInt(queryInfo.pagesize),
      ]
    )

    return this.ctx.getRESTfulData(
      {
        total: resultAll.length,
        archiveList: result,
      },
      '获取筛选档案列表成功',
      200
    )
  }
  async getSingleArchive(options) {
    let result = await this.app.mysql.select('c_archive', {
      where: options,
    })
    return this.ctx.getRESTfulData(result, '获取单个档案信息成功', 200)
  }
  async createArchive(archiveInfo) {
    const singleResult = await this.getSingleArchive({
      archive_name: archiveInfo.archive_name,
    })

    if (singleResult.data.length > 0) {
      return this.ctx.getRESTfulData(null, '该档案已存在', 401)
    }

    const result = await this.app.mysql.insert('c_archive', {
      ...archiveInfo,
    })

    if (result.affectedRows === 1) {
      const singleResult2 = await this.getSingleArchive({
        archive_id: result.insertId,
      })

      return this.ctx.getRESTfulData(singleResult2.data[0], '新增档案成功', 201)
    } else {
      return this.ctx.getRESTfulData(null, '新增档案失败', 401)
    }
  }
  async updateArchive() {}
  async deleteArchive(id) {
    let result = await this.app.mysql.delete('c_archive', {
      archive_id: id,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '档案删除成功',
          status: 200,
        },
      }
    }
  }
  // 上传单个文件
  async uploadFiles() {
    // 获取文件流
    const stream = await this.ctx.getFileStream()
    // 定义文件名 时间戳和文件后缀
    const filename =
      Date.now() + path.extname(stream.filename).toLocaleLowerCase()
    // 目标文件
    const target = path.join('app/public/uploads/manager-record', filename)
    //
    const writeStream = fs.createWriteStream(target)
    // console.log('-----------获取表单中其它数据 start--------------')
    // console.log(stream.fields)
    // console.log('-----------获取表单中其它数据 end--------------')
    try {
      //异步把文件流 写入
      await awaitStreamReady.write(stream.pipe(writeStream))
    } catch (err) {
      //如果出现错误，关闭管道
      await sendToWormhole(stream)
      return this.ctx.getRESTfulData({ error: err }, '上传失败', 401)
    }

    // 将路径返给 客户端
    return this.ctx.getRESTfulData(
      {
        filePath: path.join('/public/uploads/manager-record/', filename),
      },
      '上传成功',
      200
    )
  }
}

module.exports = ArchiveService
